import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

/// 本地存储服务 - 基于SharedPreferences的GetX服务封装
class StorageService extends GetxService {
  static StorageService get to => Get.find();
  late SharedPreferences _prefs;

  // 存储键名常量
  static const String keyToken = 'user_token';
  static const String keyUserInfo = 'user_info';
  static const String keyLanguage = 'app_language';
  static const String keyThemeMode = 'theme_mode';
  static const String keyFirstLaunch = 'first_launch';
  static const String keyRememberPassword = 'remember_password';
  static const String keyUsername = 'username';
  static const String keyPassword = 'password';
  static const String keySearchHistory = 'search_history';
  static const String keyAppSettings = 'app_settings';

  @override
  Future<void> onInit() async {
    super.onInit();
    debugPrint('🚀 StorageService 初始化中...');
    await _initPrefs();
  }

  /// 初始化SharedPreferences
  Future<void> _initPrefs() async {
    try {
      _prefs = await SharedPreferences.getInstance();
      debugPrint('✅ StorageService 初始化完成（SharedPreferences模式）');
    } catch (e) {
      debugPrint('❌ StorageService 初始化失败: $e');
      debugPrint('💡 可能的解决方案:');
      debugPrint('   1. 运行 flutter clean && flutter pub get');
      debugPrint('   2. 重启IDE和模拟器/设备');
      debugPrint('   3. 尝试在真机上运行');
      rethrow;
    }
  }

  // ==================== 基础存储方法 ====================

  /// 存储字符串
  Future<bool> setString(String key, String value) async {
    return await _prefs.setString(key, value);
  }

  /// 获取字符串
  String? getString(String key) {
    return _prefs.getString(key);
  }

  /// 存储整数
  Future<bool> setInt(String key, int value) async {
    return await _prefs.setInt(key, value);
  }

  /// 获取整数
  int? getInt(String key) {
    return _prefs.getInt(key);
  }

  /// 存储双精度数
  Future<bool> setDouble(String key, double value) async {
    return await _prefs.setDouble(key, value);
  }

  /// 获取双精度数
  double? getDouble(String key) {
    return _prefs.getDouble(key);
  }

  /// 存储布尔值
  Future<bool> setBool(String key, bool value) async {
    return await _prefs.setBool(key, value);
  }

  /// 获取布尔值
  bool? getBool(String key) {
    return _prefs.getBool(key);
  }

  /// 存储字符串列表
  Future<bool> setStringList(String key, List<String> value) async {
    return await _prefs.setStringList(key, value);
  }

  /// 获取字符串列表
  List<String>? getStringList(String key) {
    return _prefs.getStringList(key);
  }

  /// 存储对象（JSON序列化）
  Future<bool> setObject(String key, Map<String, dynamic> value) async {
    return await _prefs.setString(key, jsonEncode(value));
  }

  /// 获取对象（JSON反序列化）
  Map<String, dynamic>? getObject(String key) {
    final value = _prefs.getString(key);
    if (value != null) {
      try {
        return jsonDecode(value) as Map<String, dynamic>;
      } catch (e) {
        debugPrint('JSON解析失败: $e');
        return null;
      }
    }
    return null;
  }

  /// 检查键是否存在
  bool containsKey(String key) {
    return _prefs.containsKey(key);
  }

  /// 删除指定键
  Future<bool> remove(String key) async {
    return await _prefs.remove(key);
  }

  /// 清空所有数据
  Future<bool> clear() async {
    return await _prefs.clear();
  }

  /// 获取所有键
  Set<String> getKeys() {
    return _prefs.getKeys();
  }

  /// 获取存储统计信息
  Map<String, dynamic> getStorageStats() {
    final keys = _prefs.getKeys();
    return {
      'totalKeys': keys.length,
      'keys': keys.toList(),
      'storageType': 'SharedPreferences',
      'persistent': true,
    };
  }

  /// 打印所有存储的数据（调试用）
  void printAllData() {
    debugPrint('==================== 存储数据 ====================');
    final keys = _prefs.getKeys();
    if (keys.isEmpty) {
      debugPrint('暂无存储数据');
    } else {
      for (String key in keys) {
        final value = _prefs.get(key);
        debugPrint('$key: $value');
      }
    }
    debugPrint('================================================');
  }

  // ==================== 业务相关存储方法 ====================

  /// 保存用户Token
  Future<bool> saveToken(String token) async {
    return await setString(keyToken, token);
  }

  /// 获取用户Token
  String? getToken() {
    return getString(keyToken);
  }

  /// 获取用户Token（网络服务专用）
  String getUserToken() {
    return getToken() ?? '';
  }

  /// 检查是否已登录
  bool get isLoggedIn {
    final token = getToken();
    return token != null && token.isNotEmpty;
  }

  /// 保存用户信息
  Future<bool> saveUserInfo(Map<String, dynamic> userInfo) async {
    return await setObject(keyUserInfo, userInfo);
  }

  /// 获取用户信息
  Map<String, dynamic>? getUserInfo() {
    return getObject(keyUserInfo);
  }

  /// 保存语言设置
  Future<bool> saveLanguage(String language) async {
    return await setString(keyLanguage, language);
  }

  /// 获取语言设置
  String get language => getString(keyLanguage) ?? 'zh_CN';

  /// 保存主题模式
  Future<bool> saveThemeMode(String themeMode) async {
    return await setString(keyThemeMode, themeMode);
  }

  /// 获取主题模式
  String get themeMode => getString(keyThemeMode) ?? 'system';

  /// 检查是否首次启动
  bool get isFirstLaunch => getBool(keyFirstLaunch) ?? true;

  /// 设置首次启动标记
  Future<bool> setFirstLaunch(bool isFirst) async {
    return await setBool(keyFirstLaunch, isFirst);
  }

  /// 检查是否记住密码
  bool get rememberPassword => getBool(keyRememberPassword) ?? false;

  /// 设置记住密码
  Future<bool> setRememberPassword(bool remember) async {
    return await setBool(keyRememberPassword, remember);
  }

  /// 保存用户名
  Future<bool> saveUsername(String username) async {
    return await setString(keyUsername, username);
  }

  /// 获取用户名
  String get username => getString(keyUsername) ?? '';

  /// 保存密码
  Future<bool> savePassword(String password) async {
    return await setString(keyPassword, password);
  }

  /// 获取密码
  String get password => getString(keyPassword) ?? '';

  /// 获取搜索历史
  List<String> get searchHistory => getStringList(keySearchHistory) ?? [];

  /// 添加搜索历史
  Future<bool> addSearchHistory(String keyword) async {
    if (keyword.trim().isEmpty) return false;
    
    List<String> history = searchHistory;
    // 移除重复项
    history.remove(keyword);
    // 添加到首位
    history.insert(0, keyword);
    // 限制数量（最多20条）
    if (history.length > 20) {
      history = history.take(20).toList();
    }
    
    return await setStringList(keySearchHistory, history);
  }

  /// 清空搜索历史
  Future<bool> clearSearchHistory() async {
    return await remove(keySearchHistory);
  }

  /// 保存应用设置
  Future<bool> saveAppSettings(Map<String, dynamic> settings) async {
    return await setObject(keyAppSettings, settings);
  }

  /// 获取应用设置
  Map<String, dynamic> get appSettings => getObject(keyAppSettings) ?? {};

  /// 用户登出（清理相关数据）
  Future<bool> logout() async {
    try {
      // 清理用户相关数据
      await remove(keyToken);
      await remove(keyUserInfo);
      await remove(keyUsername);
      await remove(keyPassword);
      
      debugPrint('✅ 用户登出成功');
      return true;
    } catch (e) {
      debugPrint('❌ 用户登出失败: $e');
      return false;
    }
  }

  /// 清除用户数据（网络服务专用）
  Future<void> clearUserData() async {
    await logout();
  }
}
